package com.ruoyi.omchannel.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson2.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ruoyi.ommpuser.wxutils.OkHttpUtils;
import com.ruoyi.ommpuser.wxutils.constant.WeChatAppConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.omchannel.mapper.OmChannelMapper;
import com.ruoyi.omchannel.domain.OmChannel;
import com.ruoyi.omchannel.service.IOmChannelService;

/**
 * 渠道管理Service业务层处理
 * 
 * @author ningyi
 * @date 2025-02-11
 */
@Service
public class OmChannelServiceImpl implements IOmChannelService 
{
    @Autowired
    private OmChannelMapper omChannelMapper;

    @Value("${app.appid}")
    private String appid;
    @Value("${app.secret}")
    private String secret;
    @Value("${app.envVersion}")
    private String trial;

    /**
     * 查询渠道管理
     * 
     * @param channelId 渠道管理主键
     * @return 渠道管理
     */
    @Override
    public OmChannel selectOmChannelByChannelId(Long channelId) throws Exception {
        OmChannel omChannel = omChannelMapper.selectOmChannelByChannelId(channelId);
        String zsbImage = generateQrCodeZSB(omChannel);
        String tybImage = generateQrCodeTYB(omChannel);
        if (omChannel != null){
            omChannel.setChannelImage(zsbImage);
            omChannel.setRemark(tybImage);
        }
        return omChannel;
    }

    /**
     * 查询渠道管理列表
     * 
     * @param omChannel 渠道管理
     * @return 渠道管理
     */
    @Override
    public List<OmChannel> selectOmChannelList(OmChannel omChannel)
    {
        return omChannelMapper.selectOmChannelList(omChannel);
    }

    /**
     * 新增渠道管理
     * 
     * @param omChannel 渠道管理
     * @return 结果
     */
    @Override
    public int insertOmChannel(OmChannel omChannel)
    {
        return omChannelMapper.insertOmChannel(omChannel);
    }

    /**
     * 修改渠道管理
     * 
     * @param omChannel 渠道管理
     * @return 结果
     */
    @Override
    public int updateOmChannel(OmChannel omChannel)
    {
        return omChannelMapper.updateOmChannel(omChannel);
    }

    /**
     * 批量删除渠道管理
     * 
     * @param channelIds 需要删除的渠道管理主键
     * @return 结果
     */
    @Override
    public int deleteOmChannelByChannelIds(Long[] channelIds)
    {
        return omChannelMapper.deleteOmChannelByChannelIds(channelIds);
    }


    /**
     * 删除渠道管理信息
     * 
     * @param channelId 渠道管理主键
     * @return 结果
     */
    @Override
    public int deleteOmChannelByChannelId(Long channelId)
    {
        return omChannelMapper.deleteOmChannelByChannelId(channelId);
    }

    @Override
    public OmChannel getInfo(String uuid) {
        return omChannelMapper.getInfo(uuid);
    }

    @Override
    public String generateQrCodeZSB(OmChannel channel) throws Exception {
        String wxToken = getWXToken(appid, secret);

        // 请求 URL
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + wxToken;

        // 请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("page", "pages/index/index");
        // 构建 scene 参数
        String scene = "x=" + channel.getChannelUuid();
        if (scene.length() > 32) {
            scene = scene.substring(0, 32);
        }
        params.put("scene", scene);
        params.put("env_version", trial);
        params.put("check_path", false);

        // 将参数转换为 JSON 格式
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String jsonParams = gson.toJson(params);

        HttpURLConnection connection = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            URL apiUrl = new URL(url);
            connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            // 写入请求参数
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonParams.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (InputStream inputStream = connection.getInputStream()) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        byteArrayOutputStream.write(buffer, 0, bytesRead);
                    }
                }
                byte[] imageBytes = byteArrayOutputStream.toByteArray();
                // 将字节数组转换为 Base64 编码字符串
                return Base64.getEncoder().encodeToString(imageBytes);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    @Override
    public String generateQrCodeTYB(OmChannel channel) throws Exception {
        String wxToken = getWXToken(appid, secret);

        // 请求 URL
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + wxToken;

        // 请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("page", "pages/index/index");
        // 构建 scene 参数
        String scene = "x=" + channel.getChannelUuid();
        if (scene.length() > 32) {
            scene = scene.substring(0, 32);
        }
        params.put("scene", scene);
        params.put("env_version", "trial");
        params.put("check_path", false);

        // 将参数转换为 JSON 格式
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String jsonParams = gson.toJson(params);

        HttpURLConnection connection = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            URL apiUrl = new URL(url);
            connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

            // 写入请求参数
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonParams.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (InputStream inputStream = connection.getInputStream()) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        byteArrayOutputStream.write(buffer, 0, bytesRead);
                    }
                }
                byte[] imageBytes = byteArrayOutputStream.toByteArray();
                // 将字节数组转换为 Base64 编码字符串
                return Base64.getEncoder().encodeToString(imageBytes);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    private String getWXToken(String appid,String secret) throws Exception {
        String message = OkHttpUtils.builder().url(WeChatAppConstants.PHONETOKENURL)
                // 有参数的话添加参数，可多个
                .addParam("grant_type", "client_credential")
                .addParam("secret", secret)
                .addParam("appid", appid)
                //.addHeader("Content-Type", "application/json; charset=utf-8")
                .get()
                // 可选择是同步请求还是异步请求
                .async();
        Map<String, Object> map = JSON.parseObject(message, Map.class);
        String access_token = String.valueOf(map.get("access_token"));
        if (null==access_token){
            throw  new Exception("小程序登录失败，请联系管理员");

        }
        return access_token;

    }

}
